package edu.tsinghua.ddb.main.swing;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

import edu.tsinghua.ddb.beans.QueryTree;
import edu.tsinghua.ddb.main.gui.TreeNode;

public class Tree extends JTree {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Tree() {
		DefaultMutableTreeNode n = new DefaultMutableTreeNode();
		TreeModel newModel = new DefaultTreeModel(n);
		setModel(newModel);
	}
	
	public Tree(boolean withFrame){
		JFrame jf=new JFrame("Query Tree");
		jf.setSize(800, 600);
		jf.add(new JScrollPane(this));
		jf.setVisible(true);
	}

	private void expandAll() {
		for (int i = 0; i < getRowCount(); i++)
			expandRow(i);
	}

	public void render(QueryTree tree) {
		DefaultMutableTreeNode n = new DefaultMutableTreeNode();
		fill(tree, n);
		TreeModel newModel = new DefaultTreeModel(n);
		setModel(newModel);
		expandAll();
	}

	private void fill(TreeNode tree, DefaultMutableTreeNode n) {
		n.setUserObject(tree.toString());
		if (tree.childNodes() != null)
			for (TreeNode tn : tree.childNodes()) {
				DefaultMutableTreeNode child = new DefaultMutableTreeNode();
				fill(tn, child);
				n.add(child);
			}
	}
}
